import React from 'react';
import { Collapse, Divider } from 'antd';
import axios from 'axios';
import { useEffect, useState } from 'react'
import { Link, useParams, useNavigate } from 'react-router-dom';
import { observer } from 'mobx-react-lite'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, DatePicker, Select,Modal, Input,message,Upload ,Pagination} from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined,PlusOutlined,EllipsisOutlined  } from '@ant-design/icons'
import { useForm } from 'antd/lib/form/Form';
import moment from 'moment'; // Import moment library
const { Panel } = Collapse;

const HomeworkList = () => { 
    const navigate = useNavigate(); // 从 useNavigate() 返回的值中获取 navigate
    let { id } = useParams();
    const [form] = useForm();
    const [data, setData] = useState([]);
    const [params, setParams] = useState({
        page: 1,
        perpage: 5
    });
    let { homeworkId } = useParams();
   
    useEffect(() => {
        axios.get('http://localhost:8000/getteacherhomework', { params: { ...params, id } })
            .then(response => {
                console.log("接收到的数据", response.data.list);
    
                // Filter out items with start time later than current time
                const filteredData = response.data.list.filter(item => moment(item.start).isBefore(moment()));
    
                setData(filteredData);
                console.log("存储的数据", JSON.stringify(filteredData));
            })
            .catch(error => {
                console.error('获取数据时出错:', error);
            });
    }, [params]);

    const handlePageChange = (currentPage) => {
        setParams({ ...params, page: currentPage });
    };

    const getStatusColor = (endTime) => {
        if (moment(endTime).isBefore(moment())) {
            return 'red'; // 已截止，显示红色字体
        } else {
            return 'green'; // 进行中，显示绿色字体
        }
    };
    const formatDeadline = (deadline) => {
        return moment(deadline).format('YYYY-MM-DD HH:mm:ss');
    };

    const handleCardClick = (homeworkId, endTime) => {
        if (moment(endTime).isBefore(moment())) {
            // 如果任务已经截止，则显示警告信息
            message.warning('该任务已经截止，无法提交作业！');
        } else {
            console.log("Clicked on course with id:", homeworkId);
            navigate(`/Layoutstudent/correct/${id}/${homeworkId}`);
        }
    };
    




    return (
        <div>
            <h2>作业</h2>
            <Divider orientation="left"></Divider>
<Collapse
    size="large"
    items={data.map(item => ({
        key: item.id.toString(),
        label: (
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>
                    <b>{item.title}</b>
                </span>
                <span style={{ color: getStatusColor(item.end) }}>
                    {moment(item.end).isBefore(moment()) ? '已截止' : '进行中'}
                </span>
            </div>
        ),
        children: (
            <div style={{ width: '900px', wordWrap: 'break-word' }}>
                <p>
                <Button onClick={() => handleCardClick(item.homeworkid, item.end)}>提交作业</Button><br />
                    发布教师：{item.teachername}<br />
                    截止时间：{formatDeadline(item.end)}<br />
                    <br></br>
                    作业要求：{item.text}
                </p>
                {item?.img && (
    item.img.includes(',') ? 
    item.img.split(',').map((img, index) => (
        <img key={index} src={`http://localhost:8000/${img.trim()}`} alt={`Image ${index}`} style={{ maxWidth: '800px', maxHeight: '800px', marginRight: '100px' }} />
      )) : 
      <img src={`http://localhost:8000/${item.img.trim()}`} alt="Single Image" style={{ maxWidth: '100px', maxHeight: '100px' }} />
      
  )}
                {/* 添加其他想显示的字段 */}
            </div>
        )
    })).slice((params.page - 1) * params.perpage, params.page * params.perpage)} // 只显示当前页对应的数据条数
    style={{ width: '1000px' }}
/>

            <Pagination
                current={params.page}
                total={data.length}  // 替换为服务器端返回的总数据条数
                pageSize={params.perpage}
                onChange={handlePageChange}
                 // 设置Pagination组件靠右对齐
            />
        </div>
    );
}

export default HomeworkList;